﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using ToDoBasket.Model;

namespace ToDoBasket.Core
{
    class XmlManager
    {
        //单例实现
        private static XmlManager _instance;
        public static XmlManager Instance { get { return _instance ?? (_instance = new XmlManager()); } }
        private XmlManager(){}

        //数据文件名称
        private const string fileName = "todo.xml";

        //读取数据
        public ObservableCollection<Potato> Load()
        {
            ObservableCollection<Potato> list = new ObservableCollection<Potato>();
            if (!File.Exists(fileName)) return list;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);
                XmlElement root = doc.DocumentElement;
                XmlNodeList nodes = root.GetElementsByTagName("todo");
                foreach (XmlNode node in nodes)
                {
                    string content = node.Attributes["content"].InnerText;
                    bool? isFinished = node.Attributes["isFinished"].InnerText.Equals("True") ? true : false;
                    Potato potato = new Potato() { Original = content, IsFinished = isFinished };
                    list.Add(potato);
                }
            }
            catch (Exception)
            {
                return new ObservableCollection<Potato>();
            }
            return list;
        }

        //保存数据
        public void Save(ObservableCollection<Potato> list)
        {
            XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("basket");
            //todo:保存窗体大小
            foreach (Potato potato in list)
            {
                writer.WriteStartElement("todo");
                writer.WriteAttributeString("content", potato.Original);
                writer.WriteAttributeString("isFinished", potato.IsFinished.ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }
    }
}
